﻿using System;
using System.Collections.Generic;
using UnityEngine;

public class UIManager
{
    private UnityGameObject gameObjRootUI = new UnityGameObject();

    private Dictionary<Type, IUIBase> windows = new Dictionary<Type, IUIBase>();

    private static readonly UIManager instance = new UIManager();
    public static UIManager GetInstance()
    {
        return instance;
    }

    /// <summary>
    /// 创建类工厂
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <returns></returns>
    public IUIBase CreateFactory<T>() where T : IUIBase
    {
        if (typeof(T) == typeof(MainUI))
        {
            return new MainUI();
        }
        else if (typeof(T) == typeof(StartUI))
        {
            return new StartUI();
        }
        else if (typeof(T) == typeof(ReStartUI))
        {
            return new ReStartUI();
        }
        else
        {
            return default(T);
        }
    }

    public void Start()
    {
        gameObjRootUI.Instantiate("UI/UIRoot", Vector3.zero, Quaternion.identity);
    }

    /// <summary>
    /// 获取没有则创建
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <returns></returns>
    public T GetUI<T>() where T : IUIBase
    {
        string name = typeof(T).ToString();
        if (windows.ContainsKey(typeof(T)))
        {
            return (T)windows[typeof(T)];
        }
        else
        {
            IUIBase newIUIBase = CreateFactory<T>();

            windows.Add(newIUIBase.GetType(), newIUIBase);

            return (T)newIUIBase;
        }
    }

    /// <summary>
    /// 移除
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public void RemoveWindow<T>() where T : IUIBase
    {
        string name = typeof(T).ToString();

        if (windows.ContainsKey(typeof(T)))
        {
            windows[typeof(T)].Destroy();

            windows.Remove(typeof(T));
        }
    }

    /// <summary>
    /// 更新
    /// </summary>
    /// <param name="deltaTime"></param>
    public void Update(float deltaTime)
    {
        foreach (IUIBase ui in windows.Values)
        {
            ui.Update(deltaTime);
        }
    }

}
